<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button> -->
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" @click="handleCreate">
        新增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="true"
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-table :data="row.collection_items" :border="true" class="expand-table">
            <el-table-column label="类型">
              <template slot-scope="scope">
                {{ scope.row.item_category | getItemCategory }}
              </template>
            </el-table-column>
            <el-table-column label="名称" prop="item_name" />
          </el-table>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" min-width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="customer_id">
        <template slot-scope="scope">
          <span>{{ scope.row.customer_id }}</span>
        </template>
      </el-table-column> -->

      <el-table-column min-width="120px" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.collection_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作逻辑" prop="collection_logic_operator">
        <template slot-scope="scope">
          <span>{{ scope.row.collection_logic_operator | getCollectionLogicOperator }}</span>
        </template>
      </el-table-column>
      <el-table-column label="错误码" prop="collection_output_code" />

      <el-table-column align="center" label="操作">
        <template slot-scope="{ row }">
          <el-button type="primary" size="small" @click="testCollection(row.id)">
            测试
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog title="策略集" :visible.sync="dialogVisible">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="collection_name">
          <el-input v-model="form.collection_name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.collection_description" type="textarea" />
        </el-form-item>
        <el-form-item v-for="(collection_item, index) in form.collection_items" :key="index" label="策略类型">
          <el-row :gutter="10">
            <el-col :span="10">

              <el-select
                v-model="collection_item.item_category"
                placeholder="策略类型"
                clearable
                class="filter-item"
                @change="cateChange($event, index)"
              >
                <el-option v-for="item in itemCategory" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="collection_item.item_id_within_category"
                placeholder="策略类型类型id"
                clearable
                class="filter-item"
              >
                <el-option v-for="item in cateData[index]" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :span="2">
              <el-button v-show="form.collection_items.length>1" size="mini" type="primary" @click="delParameter(index)">删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="">
          <el-button size="mini" type="success" @click="addParameter">添加</el-button>
        </el-form-item>
        <el-form-item label="操作逻辑" prop="collection_logic_operator">
          <el-select v-model="form.collection_logic_operator" placeholder="操作逻辑">
            <el-option v-for="item in collectionLogicOperator" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="错误码" prop="collection_output_code">
          <el-input v-model.number="form.collection_output_code" />
        </el-form-item>
        <el-form-item label="错误信息" prop="collection_output_message">
          <el-input v-model="form.collection_output_message" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="策略测试" :visible.sync="testDialogVisible" width="70%">
      <json-editor ref="jsonEditor" v-model="testJson" />
      <aside v-show="result" style="" class="dialog-aside" :class="{bgColor: resultSuccess}">
        命中结果：
        <json-viewer :value="result" />
      </aside>
      <div slot="footer" class="dialog-footer">
        <el-button @click="testDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTest">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, create, test } from '@/api/collection'
import { itemCategory, collectionLogicOperator } from '@/utils/options'
import Pagination from '@/components/Pagination'
import JsonEditor from '@/components/JsonEditor'
import JsonViewer from 'vue-json-viewer'
const item = {
  item_category: '',
  item_id_within_category: undefined
}

const defaultForm = {
  collection_name: '',
  collection_logic_operator: '',
  collection_description: '',
  collection_items: [
    Object.assign({}, item)
  ],
  collection_output_code: undefined,
  collection_output_message: ''
}

export default {
  name: 'Collection',
  components: { Pagination, JsonEditor, JsonViewer },
  filters: {
    getItemCategory(cate) {
      const cateItem = itemCategory.find(item => {
        return item.value === cate
      })
      return cateItem.label
    },
    getCollectionLogicOperator(val) {
      const obj = collectionLogicOperator.find(item => {
        return item.value === val
      })
      return obj.label
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      form: defaultForm,
      itemCategory: itemCategory,
      collectionLogicOperator: collectionLogicOperator,
      rules: {
        collection_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        collection_logic_operator: [{ required: true, message: '请选择逻辑关系', trigger: 'blur' }],
        collection_output_code: [
          { required: true, message: '请输入返回错误码', trigger: 'blur' },
          { type: 'number', message: 'code必须为数字值' }
        ],
        collection_output_message: [{ required: true, message: '请输入错误信息', trigger: 'blur' }]
      },
      remoteFunc: undefined,
      cateData: {},
      dialogVisible: false,
      testDialogVisible: false,
      current_id: 0,
      testJson: JSON.parse('{}'),
      result: '',
      resultSuccess: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.list
        this.total = response.total
        this.listLoading = false
      })
    },
    handleCreate() {
      this.form = Object.assign({}, defaultForm)
      this.$set(this.form, 'collection_items', [Object.assign({}, item)])
      this.dialogVisible = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          create(this.form).then(rep => {
            this.$message({
              message: '数据保存成功',
              type: 'success'
            })
            this.getList()
            this.dialogVisible = false
          })
        } else {
          this.$message.error('提交失败，请检查提交数据')
          return false
        }
      })
    },
    addParameter() {
      this.form.collection_items.push(Object.assign({}, item))
    },
    delParameter(index) {
      this.form.collection_items.splice(index, 1)
    },
    async cateChange(key, index) {
      // console.log(key, index)
      const obj = itemCategory.find(item => key === item.value)
      this.remoteFunc = obj.func

      const rep = await this.remoteFunc({ page: 1, limit: 100 })
      var data = rep.list

      data = data.map(ele => {
        // const name = obj.value + '_name'
        return {
          value: ele.id,
          label: ele[obj.value + '_name']
        }
      })
      this.$set(this.cateData, index, data)
      this.$set(this.form.collection_items[index], 'item_id_within_category', '')
      // console.log(this.cateData)
    },
    testCollection(id) {
      if (this.current_id !== id) this.result = ''
      this.testDialogVisible = true
      this.current_id = id
    },
    submitTest() {
      // console.log(this.testJson)
      test(this.current_id, this.testJson).then(rep => {
        console.log(rep)
        this.result = rep
        this.resultSuccess = rep.winning
      })
    }
  }
}
</script>

<style lang="scss">
  .dialog-aside{
    background-color: #aaaaaa;
    &.bgColor{
      background-color: #42b983;
    }
  }

  .el-table.expand-table{
    font-size: 16px;
    width: 60%;
    th {
      background-color: #42b983;
      color: #fff;
      font-weight: bold;
    }
    td{
       color: #42b983;
       background-color: #f1f1f1;
    }

  }

</style>
